package homework013;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Server implements Runnable {

    private Integer port;

    Server(Integer port) throws IOException {
        this.port = port;
    }

    @Override
    public void run() {
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        Socket accept = null;
        try {
            accept = ss.accept();
            InputStream is = accept.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(is, StandardCharsets.UTF_8);

            int read;
            while (true) {
                read = inputStreamReader.read();

                // -1代表发送端断开连接
                // 接收端也可以相应断开连接
                if (read == -1) {
                    System.out.println("断开");
                    is.close();
                    accept.close();
                    break;
                }

                System.out.print((char) read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
